/**
 * Created by zhoumingrui on 2017/1/14.
 */
class Event {
    constructor() {
        this.__message = {};
    }

    regist(type, fn) {
        if (typeof this.__message[type] === 'undefined') {
            this.__message[type] = [fn];
        } else {
            this.__message[type].push(fn);
        }
    }

    fire(type, args) {
        if (!this.__message[type]) {
            return;
        }

        let events = {
            type: type,
            args: args || {}
        };

        this.__message[type].map((fn)=>{
            fn.call(this, events);
        });
    }

    remove(type, fn) {
        if (this.__message[type] instanceof Array) {
            let i = this.__message[type].length - 1;
            if (!fn) {
                this.__message[type] = [];
            } else {
                for (; i >= 0; i--) {
                    this.__message[type][i] === fn && this.__message[type].splice(i, 1);
                }
            }
        }
    }
}

module.exports = Event;